<template>
  <div>
    <div class="content-m flex-center">
      <div class="create-form">
        <div style="text-align: center">
          <h1>
            发布失物招领信息
          </h1>
          <p>
            填写以下表单发布失物或招领信息，帮助物品物归原主
          </p>
        </div>
        <div class="flex-center" style="margin-top: 20px">
          <el-radio-group v-model="formType" size="large">
            <el-radio-button label="丢失物品" value="lost"/>
            <el-radio-button label="拾获物品" value="found"/>
          </el-radio-group>
        </div>
        <el-card style="margin-top: 30px">
          <template #header>
            物品信息
          </template>
          <el-form v-if="formType==='lost'" :model="lostItemsForm" label-width="120px" label-position="top"
                   ref="lostItemsFormRef" size="large">
            <el-form-item label="默认图片">
              <el-upload
                  v-model:file-list="lostImageFileList"
                  :action="$fileUpload"
                  :headers="$getHeaders"
                  :data="{sceneCode:'serve:lost-found'}"
                  :on-success="handleAvatarSuccess"
                  list-type="picture-card"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="失物名称">
                  <el-input v-model="lostItemsForm.itemName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启事标题">
                  <el-input v-model="lostItemsForm.title"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物品状态">
                  <el-input v-model="lostItemsForm.objectStatus"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急程度">
                  <el-input v-model="lostItemsForm.emergencyLevel"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="丢失时间">
                  <el-date-picker
                      v-model="lostItemsForm.lostTime"
                      type="datetime"
                      style="width: 100%;"
                      placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分类">
                  <el-select
                      v-model="lostItemsForm.categoryId"
                      placeholder="Select"
                      size="large"
                  >
                    <el-option
                        v-for="item in lostFoundCategoryList"
                        :key="item.lostFoundCategoryId"
                        :label="item.name"
                        :value="item.lostFoundCategoryId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学校编号">
                  <el-input v-model="lostItemsForm.schoolId"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="丢失地点">
                  <el-input v-model="lostItemsForm.location"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="描述">
              <el-input v-model="lostItemsForm.description" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="lostItemsForm.remark" type="textarea"></el-input>
            </el-form-item>
            <el-button type="primary" @click="submitLostForm(lostItemsFormRef)" style="width: 100%">发布</el-button>
          </el-form>
          <el-form v-else :model="lostItemsForm" label-width="120px" label-position="top" ref="lostItemsFormRef"
                   size="large">
            <el-form-item label="默认图片">
              <el-upload
                  :action="$fileUpload"
                  v-model:file-list="foundImageFileList"
                  :headers="$getHeaders"
                  :on-remove="handleRemove"
                  :data="{sceneCode:'serve:lost-found'}"
                  list-type="picture-card"
                  :on-success="handleFoundSuccess"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="物品状态">
              <el-input v-model="lostItemsForm.objectStatus"></el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="失物名称">
                  <el-input v-model="foundItemForm.itemName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="启事标题">
                  <el-input v-model="foundItemForm.title"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="丢失时间">
                  <el-date-picker
                      v-model="lostItemsForm.lostTime"
                      type="datetime"
                      style="width: 100%;"
                      placeholder="选择日期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="分类">
                  <el-select
                      v-model="lostItemsForm.categoryId"
                      placeholder="选择分类"
                  >
                    <el-option
                        v-for="item in lostFoundCategoryList"
                        :key="item.lostFoundCategoryId"
                        :label="item.name"
                        :value="item.lostFoundCategoryId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学校编号">
                  <el-input v-model="foundItemForm.schoolId"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发现地点">
                  <el-input v-model="foundItemForm.location"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="描述">
              <el-input v-model="foundItemForm.description" type="textarea"></el-input>
            </el-form-item>
            <el-button type="primary" @click="submitFoundItem(foundItemsFormRef)" style="width: 100%">发布</el-button>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref, watch} from "vue";
import {useRouter, useRoute} from "vue-router";
import {
  reqGetLostItemPage,
  reqAddLostItem,
  reqUpdateLostItem,
  reqDeleteLostItem,
  reqGetLostItemById, reqGetLostFoundCategoryList, reqAddFoundItem, reqGetFoundItemById, reqUpdateFoundItem
} from "@/api/serve/lost";
import type {FormInstance} from "element-plus";
import {ArrowRight, Plus} from '@element-plus/icons-vue'
import {useUserStore} from "@/stores/user";
import type {LostItems, LostFoundCategory} from "@/api/serve/lost/type";
import type {FoundItems} from "@/api/serve/lost/type";

let userStore = useUserStore();
let route = useRoute();
let isEditing = computed(() => {
  return route.params.itemId != null
});
const router = useRouter();
let lostItemsFormRef = ref<FormInstance>();
let formType = ref("lost");
let lostImageFileList = ref([])
let lostItemsForm = reactive({
  lostItemId: "",
  userId: userStore.userId,
  itemName: "",
  description: "",
  location: "",
  lostTime: null,
  defaultPicture: "",
  categoryId:'',
  status: 0,
  createTime: null,
  updateTime: null,
  remark: "",
  schoolId: "",
  title: '',
  emergencyLevel: '',
  objectStatus: '',
  picUrls: []
});
let lostFoundCategoryList = ref<LostFoundCategory[]>([])

let getLostFoundCategoryList = async () => {
  let res = await reqGetLostFoundCategoryList()
  lostFoundCategoryList.value = res.data
}
let handleAvatarSuccess = (res) => {
  lostItemsForm.picUrls.push(res.data.visitPath)
}
let submitLostForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isEditing.value){
        await reqUpdateLostItem(lostItemsForm)
      }else await reqAddLostItem(lostItemsForm);
      router.push({
        name: 'lost-found'
      })
    } else console.log("error submit!", fields);
  });
}
/*拾物*/
let foundItemsFormRef = ref<FormInstance>();
let foundImageFileList = ref([])
let foundItemForm = reactive({
  userId: userStore.userId,
  itemName: "",
  description: "",
  location: "",
  foundTime: null,
  defaultPicture: "",
  categoryId:'',
  status: 0,
  createTime: null,
  updateTime: null,
  schoolId: "",
  title: "",
  objectStatus: '',
  picUrls: []
});
let handleFoundSuccess = (res) => {
  foundItemForm.picUrls.push(res.data.visitPath)
}
let submitFoundItem = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isEditing.value){
        await reqUpdateFoundItem(foundItemForm)
      }
      else await reqAddFoundItem(foundItemForm);
      router.push({
        name: "lost-found"
      })
    } else console.log("error submit!", fields);
  });
}
onMounted(async () => {
  if (isEditing.value) {
    if (route.query.type === 'lost') {
      let res = await reqGetLostItemById(route.params.itemId as string)
      Object.assign(lostItemsForm, res.data)
      /*图片显示*/
      lostImageFileList.value=res.data.picUrls.map(item=>{
        return {
          url: item,
          uid: Date.now() + Math.random()
        }
      })
    } else if (route.query.type === 'found') {
      let res = await reqGetFoundItemById(route.params.itemId as string)
      Object.assign(foundItemForm, res.data)
      foundImageFileList.value=res.data.picUrls.map(item=>{
        return {
          url: item,
          uid: Date.now() + Math.random()
        }
      })
    }
  }
  getLostFoundCategoryList()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.create-form {
  padding: 20px;
  width: 800px;
  margin-top: 20px;
}
</style>

